package com.chinawlx.wlxteacher.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXClazzListBean;
import com.chinawlx.wlxteacher.ui.activity.MainActivity;
import com.chinawlx.wlxteacher.ui.adapter.WLXClazzListAdapter;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXNetUtil;
import com.chinawlx.wlxteacher.utils.WLXTeacherConstant;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.wlx_grade;
import com.chinawlx.wlxteacher.wlx_gradeDao;
import com.chinawlx.wlxteacher.wlx_homework_statistics;
import com.chinawlx.wlxteacher.wlx_homework_statisticsDao;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.refreshlayout.BGAMeiTuanRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import rx.Subscriber;

/**
 * Created by wlx on 16/8/9.
 */
public class WLXClazzListFragment extends WLXBaseFragment implements BGARefreshLayout
        .BGARefreshLayoutDelegate {
    private int paging_index = 1;//分页索引
    private int paging_size = 10;//每页大小
    private boolean mHasMoreData = true;

    @BindView(R.id.rl_modulename_refresh)
    BGARefreshLayout mRefreshLayout;
    @BindView(R.id.rl_container_empty)
    RelativeLayout mRlContainerEmpty;
    @BindView(R.id.tv_msg)
    TextView mTvMsg;
    @BindView(R.id.lv_clazz_list)
    ListView clazzListView;

    private List<wlx_grade> gradeList;
    private WLXLoadingFragment loadingFragment;
    private WLXClazzListAdapter clazzListAdapter;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_clazz_list, null);
        ButterKnife.bind(this, view);
        init();
        return view;
    }


    private void init() {
        initView();
    }

    private void initView() {
        initAdapter();
        initRefreshLayout();
        mRefreshLayout.beginRefreshing();
    }

    private void initAdapter() {
        clazzListAdapter = new WLXClazzListAdapter(mContext);
        clazzListView.setAdapter(clazzListAdapter);
        clazzListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String grade_id = gradeList.get(position).getGrade_id();
//                String clazzTitle = gradeList.get(position).getTitle();
                wlx_grade wlx_grade = (wlx_grade) clazzListAdapter.getItem(position);
                String grade_id = wlx_grade.getGrade_id();
                String clazzTitle = wlx_grade.getTitle();
                WLXLogUtil.printE("grade_id: "+grade_id+"clazzTitle: "+clazzTitle);
//                WLXSharedPreferenceUtil.put(getContext(),WLXTeacherConstant.GRADE_TITLE,
//              clazzTitle);
//                WLXConstant.GRADE_TITLE = clazzTitle;
//                WLXConstant.GRADE_ID = grade_id;

//                WLXSharedPreferenceUtil.put(getContext(), WLXTeacherConstant.GRADE_TITLE,
//                        clazzTitle);
//                WLXSharedPreferenceUtil.put(getContext(), WLXTeacherConstant.GRADE_ID, grade_id);
                Bundle bundle = new Bundle();
                bundle.putString(WLXTeacherConstant.GRADE_TITLE, clazzTitle);
                bundle.putString(WLXTeacherConstant.GRADE_ID, grade_id);
                startActivity(MainActivity.class, false, bundle);
            }
        });
    }
    //--------刷新内容 start---------

    private void initRefreshLayout() {
        mRefreshLayout.setDelegate(this);
        BGAMeiTuanRefreshViewHolder meiTuanRefreshViewHolder = new BGAMeiTuanRefreshViewHolder
                (this.getContext(), true);
        meiTuanRefreshViewHolder.setPullDownImageResource(R.drawable.yuanq);
        meiTuanRefreshViewHolder.setChangeToReleaseRefreshAnimResId(R.drawable
                .bga_refresh_mt_change_to_release_refresh);
        meiTuanRefreshViewHolder.setRefreshingAnimResId(R.drawable.bga_refresh_mt_refreshing);

        mRefreshLayout.setRefreshViewHolder(meiTuanRefreshViewHolder);
    }

    //开始刷新
    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.CheckNetwork(getActivity())) {
            paging_index = 1;
            requestDataFromNet();
        } else {
//            WLXCustomToast.show("无网络!");
            mRefreshLayout.endRefreshing();
            initDataFromDataBase();
        }
    }


    //处理上拉加载,在这里上拉加载更多,
    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.CheckNetwork(getActivity())) {
            if (mHasMoreData) {
                paging_index++;
                requestDataFromNet();
                return true;
            } else {
                WLXCustomToast.show("没有更多数据");
                return false;
            }
        } else {
//            WLXCustomToast.show("无网络!");
            initDataFromDataBase();
            return false;
        }
    }

    //-----------刷新 end------
    private void requestDataFromNet() {
        loadingFragment = WLXLoadingFragment.getInstance();
        loadingFragment.show(getActivity().getSupportFragmentManager(), "");
        WLXHttpRxHelper.getInstance().getClazzList(paging_index + "", paging_size + "", new
                Subscriber<WLXClazzListBean>() {


                    //从数据库取数据
                    @Override
                    public void onCompleted() {
                        initDataFromDataBase();
                        loadingFragment.dismiss();

                    }

                    //网络异常,从数据库取数据
                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }

                    //存数据到数据库
                    @Override
                    public void onNext(WLXClazzListBean wlxClazzListBean) {
                        if (wlxClazzListBean.getCode() == 0) {
                            saveGradeListTable(wlxClazzListBean);
                            savaHomeworkStatisticsTable(wlxClazzListBean);

                        }

                    }
                });
    }


    /**
     * 存储 wlx_homework_statistics 表
     *
     * @param wlxClazzListBean
     */
    private void savaHomeworkStatisticsTable(WLXClazzListBean wlxClazzListBean) {
        List<WLXClazzListBean.DataBean.HomeworkStatisticsListBean> statistics_list =
                wlxClazzListBean.getData().getHomework_statistics_list();
        for (WLXClazzListBean.DataBean.HomeworkStatisticsListBean bean :
                statistics_list) {
            String homework_statistics_id = Integer.toString(bean.getId());
            int grade_id = bean.getGrade_id();
            int homework_count = bean.getHomework_count();
            int teacher_comment_count = bean.getTeacher_comment_count();
            int family_comment_count = bean.getFamily_comment_count();
            long last_modified_date = WLXDateUtil.getStringToDate(bean.getLast_modified_date());
            wlx_homework_statistics wlxHomeworkStatistics = new wlx_homework_statistics
                    (homework_statistics_id, grade_id, homework_count,
                            teacher_comment_count, family_comment_count, last_modified_date);
            List<wlx_homework_statistics> homeworkStatisticses = WLXGreenDaoUtil
                    .getHomeworkStatisticsDao()
                    .queryBuilder().where(wlx_homework_statisticsDao.Properties
                            .Homework_statistics_id.eq(homework_statistics_id)).list();
            if (homeworkStatisticses.size() > 0) {
                if (last_modified_date > homeworkStatisticses.get(0).getLast_modified_date()) {
                    WLXGreenDaoUtil.getHomeworkStatisticsDao().update
                            (wlxHomeworkStatistics);
                }
            } else {
                WLXGreenDaoUtil.getHomeworkStatisticsDao().insert(wlxHomeworkStatistics);
            }
        }
    }

    /**
     * 存储 wlx_grade 表
     *
     * @param wlxClazzListBean
     */
    private void saveGradeListTable(WLXClazzListBean wlxClazzListBean) {
        List<WLXClazzListBean.DataBean.GradeListBean> grade_list = wlxClazzListBean
                .getData().getGrade_list();
        WLXLogUtil.printE("grade_list条数:" + grade_list.size());
        for (WLXClazzListBean.DataBean.GradeListBean grade : grade_list) {
            String grade_id = Integer.toString(grade.getId());
            WLXConstant.GRADE_ID = grade_id;
            int teacher_user_id = grade.getUser_id();
            int org_user_id = grade.getOrg_user_id();
            int space_id = grade.getSpace_id();
            int classroom_id = grade.getClassroom_id();
            String title = grade.getTitle();
            String summary = grade.getSummary();
            int min_student_count = grade.getMin_student_count();
            int max_student_count = grade.getMax_student_count();
            int student_count = grade.getStudent_count();
            int class_count = grade.getClass_count();
            long opening_date = WLXDateUtil.getStringToDate(grade
                    .getOpening_date());
            long closing_date = WLXDateUtil.getStringToDate(grade
                    .getClosing_date());
            long starting_date = WLXDateUtil.getStringToDate(grade
                    .getStarting_date());
            String class_duration = grade.getClass_duration()
                    .getValue();
            String class_type_code = grade.getClass_type()
                    .getCode();
            String class_type_name = grade.getClass_type()
                    .getName();
            String grade_type_code = grade.getGrade_type()
                    .getKey();
            String grade_type_name = grade.getGrade_type()
                    .getValue();
            long last_modified_date = WLXDateUtil.getStringToDate(grade
                    .getLast_modified_date());
            //插入班级数据
            wlx_grade wlxGrade = new wlx_grade(grade_id, teacher_user_id,
                    org_user_id,
                    space_id, classroom_id,
                    title, summary, min_student_count, max_student_count,
                    student_count, class_count, opening_date, closing_date,
                    starting_date, class_type_code, class_type_name,
                    class_duration, grade_type_code, grade_type_name,
                    last_modified_date);
            //1,查询user_id这条记录,user_id是唯一的
            List<wlx_grade> wlx_grades = WLXGreenDaoUtil.getGradeDao()
                    .queryBuilder()
                    .where(wlx_gradeDao
                            .Properties.Grade_id.eq(WLXConstant.GRADE_ID)).list();
            if (wlx_grades.size() > 0) {
                WLXLogUtil.printE("user查询到的指定id记录信息:" + grade
                        .toString());
                //2, 有这条记录, 就去对比last_modified_date, 如果服务器时间更新, 就update表数据
                if (last_modified_date > WLXDateUtil.getStringToDate(grade
                        .getLast_modified_date())) {
                    WLXGreenDaoUtil.getGradeDao().update(wlxGrade);
                }
            } else {
                //无数据,就直接插入数据
                WLXGreenDaoUtil.getGradeDao().insert(wlxGrade);
            }
        }
    }

    private void initDataFromDataBase() {
        gradeList = WLXGreenDaoUtil.getGradeDao().queryBuilder().where(wlx_gradeDao.Properties
                .Teacher_user_id.eq(WLXConstant.USER_ID)).offset((paging_index - 1) *
                paging_size).limit(paging_size).list();
        //是否有更多数据
        mHasMoreData =gradeList.size()!=0;
        if (paging_index == 1) {//下拉刷新,直接加载所有的未点评数据
            mRefreshLayout.endRefreshing();
            clazzListAdapter.setData(gradeList);
            clazzListAdapter.notifyDataSetChanged();

            if (gradeList.size()==0) {
                mRefreshLayout.setVisibility(View.GONE);
                mRlContainerEmpty.setVisibility(View.VISIBLE);
                mTvMsg.setText("暂无数据");
                return;
            }

        }else {
            mRefreshLayout.endLoadingMore();
            //上拉刷新,只需要刷新历史数据
            if (mHasMoreData) {
                int count = clazzListAdapter.getCount();
                clazzListAdapter.addData(gradeList);
                clazzListAdapter.notifyDataSetChanged();
                clazzListView.setSelection(count);
            } else {
                WLXCustomToast.show("没有更多数据");
            }
        }
//
//        clazzListView.setAdapter(new WLXClazzListAdapter(mContext, gradeList));
//        clazzListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String grade_id = gradeList.get(position).getGrade_id();
//                String clazzTitle = gradeList.get(position).getTitle();
////                WLXSharedPreferenceUtil.put(getContext(),WLXTeacherConstant.GRADE_TITLE,
//// clazzTitle);
//                WLXConstant.GRADE_TITLE = clazzTitle;
//                WLXConstant.GRADE_ID = grade_id;
//
//                WLXSharedPreferenceUtil.put(getContext(), WLXTeacherConstant.GRADE_TITLE,
//                        clazzTitle);
//                WLXSharedPreferenceUtil.put(getContext(), WLXTeacherConstant.GRADE_ID, grade_id);
//                Bundle bundle = new Bundle();
//                bundle.putString(WLXTeacherConstant.GRADE_TITLE, clazzTitle);
//                bundle.putString(WLXTeacherConstant.GRADE_ID, grade_id);
//                startActivity(MainActivity.class, false, bundle);
//            }
//        });
    }


}
